import json
import logging
from datetime import datetime, date

from django.views import View
from django.http import JsonResponse
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import extend_schema, OpenApiParameter
from rest_framework.response import Response
from rest_framework.views import APIView

from app.models import MerchantInfo, User, Employee
from app.services.employee_services import (
    EmployeeService, AttendanceService, EmployeeActivityService,
    LeaveRequestService, PerformanceService, SalaryService
)
from middleware.util import make_response, AUTH_HEADER_PARAM

logger = logging.getLogger(__name__)


@extend_schema(
    tags=["员工管理"],
    summary="创建员工档案（商家专用）",
    parameters=[AUTH_HEADER_PARAM],
    request={
        "application/json": {
            "example": {
                "user_id": "123e4567-e89b-12d3-a456-426614174000",
                "real_name": "张三",
                "hire_date": "2024-01-15",
                "work_start_time": "09:00:00",
                "work_end_time": "18:00:00",
                "base_daily_salary": 200.00,
                "work_schedule": {
                    "monday": True,
                    "tuesday": True,
                    "wednesday": True,
                    "thursday": True,
                    "friday": True,
                    "saturday": False,
                    "sunday": False
                },
                "late_penalty_per_minute": 1.0,
                "early_leave_penalty_per_minute": 1.0,
                "activity_bonus_per_count": 5.0
            }
        }
    }
)
class CreateEmployeeView(APIView):
    def post(self, request):
        """
        接口：创建员工档案
        请求头需包含 Authorization: Bearer <token>
        """
        try:
            user_id = getattr(request, 'user_id', None)
            role = getattr(request, 'role', None)

            if not user_id or role != 'merchant':
                return make_response(code=403, message="权限不足")

            try:
                user = User.objects.get(id=user_id)
                merchant_info = MerchantInfo.objects.get(merchant_id=user_id)
            except (User.DoesNotExist, MerchantInfo.DoesNotExist):
                return make_response(code=403, message="您不是合法的商家用户")

            data = json.loads(request.body)

            return EmployeeService.create_employee(
                user_id=data.get("user_id"),
                merchant_id=merchant_info.merchant_id,
                real_name=data.get("real_name"),
                hire_date=datetime.strptime(data.get("hire_date"), "%Y-%m-%d").date(),
                work_start_time=datetime.strptime(data.get("work_start_time"), "%H:%M:%S").time(),
                work_end_time=datetime.strptime(data.get("work_end_time"), "%H:%M:%S").time(),
                base_daily_salary=data.get("base_daily_salary"),
                work_schedule=data.get("work_schedule"),
                late_penalty_per_minute=data.get("late_penalty_per_minute", 0),
                early_leave_penalty_per_minute=data.get("early_leave_penalty_per_minute", 0),
                activity_bonus_per_count=data.get("activity_bonus_per_count", 0)
            )

        except json.JSONDecodeError:
            return Response({
                "code": 400,
                "message": "请求体格式错误"
            }, status=400)
        except ValueError as e:
            return Response({
                "code": 400,
                "message": f"日期时间格式错误：{str(e)}"
            }, status=400)
        except Exception as e:
            return Response({
                "code": 500,
                "message": f"系统错误：{str(e)}"
            }, status=500)

@extend_schema(
    tags=["员工管理"],
    summary="通过用户名创建员工档案（商家专用）",
    parameters=[AUTH_HEADER_PARAM],
    request={
        "application/json": {
            "example": {
                "username": "zhangsan",
                "real_name": "张三",
                "hire_date": "2024-01-15",
                "work_start_time": "09:00:00",
                "work_end_time": "18:00:00",
                "base_daily_salary": 200.00,
                "work_schedule": {
                    "monday": True,
                    "tuesday": True,
                    "wednesday": True,
                    "thursday": True,
                    "friday": True,
                    "saturday": False,
                    "sunday": False
                },
                "salary_params": {
                    "late_penalty_per_minute": 1.0,
                    "early_leave_penalty_per_minute": 1.0,
                    "activity_bonus_per_count": 5.0
                }
            }
        }
    }
)
class CreateEmployeeByUsernameView(APIView):
    def post(self, request):
        """
        接口：通过用户名创建员工档案
        请求头需包含 Authorization: Bearer <token>
        
        请求体字段说明：
        - username: 用户名（必填）
        - real_name: 真实姓名（必填）
        - hire_date: 入职日期，格式: YYYY-MM-DD（必填）
        - work_start_time: 上班时间，格式: HH:MM:SS（必填）
        - work_end_time: 下班时间，格式: HH:MM:SS（必填）
        - base_daily_salary: 基础日薪（必填）
        - work_schedule: 工作安排，布尔值字典（可选）
        - salary_params: 薪资参数（可选）
        """
        try:
            user_id = getattr(request, 'user_id', None)
            role = getattr(request, 'role', None)

            if not user_id or role != 'merchant':
                return make_response(code=403, message="权限不足")

            try:
                user = User.objects.get(id=user_id)
                merchant_info = MerchantInfo.objects.get(merchant_id=user_id)
            except (User.DoesNotExist, MerchantInfo.DoesNotExist):
                return make_response(code=403, message="您不是合法的商家用户")

            data = json.loads(request.body)

            # 验证必填字段
            required_fields = ['username', 'real_name', 'hire_date', 'work_start_time', 'work_end_time', 'base_daily_salary']
            for field in required_fields:
                if not data.get(field):
                    return Response({
                        "code": 400,
                        "message": f"字段 '{field}' 不能为空"
                    }, status=400)

            return EmployeeService.create_employee_by_username(
                username=data.get("username"),
                merchant_id=merchant_info.merchant_id,
                real_name=data.get("real_name"),
                hire_date=datetime.strptime(data.get("hire_date"), "%Y-%m-%d").date(),
                work_start_time=datetime.strptime(data.get("work_start_time"), "%H:%M:%S").time(),
                work_end_time=datetime.strptime(data.get("work_end_time"), "%H:%M:%S").time(),
                base_daily_salary=data.get("base_daily_salary"),
                work_schedule=data.get("work_schedule"),
                **data.get("salary_params", {})
            )

        except json.JSONDecodeError:
            return Response({
                "code": 400,
                "message": "请求体格式错误"
            }, status=400)
        except ValueError as e:
            return Response({
                "code": 400,
                "message": f"日期时间格式错误：{str(e)}"
            }, status=400)
        except Exception as e:
            return Response({
                "code": 500,
                "message": f"系统错误：{str(e)}"
            }, status=500)

            
@extend_schema(
    tags=["员工管理"],
    summary="更新员工信息（商家专用）",
    parameters=[AUTH_HEADER_PARAM],
    request={
        "application/json": {
            "example": {
                "real_name": "李四",
                "work_start_time": "08:30:00",
                "work_end_time": "17:30:00",
                "base_daily_salary": 220.00,
                "employment_status": "resigned",  # 新增：支持修改员工状态
                "work_schedule": {
                    "monday": True,
                    "tuesday": True,
                    "wednesday": True,
                    "thursday": True,
                    "friday": True,
                    "saturday": False,
                    "sunday": False
                },
                "salary_config": {
                    "late_penalty_per_minute": 1.5,
                    "early_leave_penalty_per_minute": 1.5,
                    "activity_bonus_per_count": 8.0
                }
            }
        }
    }
)
class UpdateEmployeeView(APIView):
    def put(self, request, user_id):
        """
        接口：更新员工信息
        URL 示例：/merchant/employee/update/123e4567-e89b-12d3-a456-426614174000/
        :param user_id: 员工的用户ID
        
        新增功能：
        - 支持修改 employment_status（active/resigned）
        - 可以将在职员工设置为离职，或将离职员工恢复为在职
        """
        try:
            request_user_id = getattr(request, 'user_id', None)
            role = getattr(request, 'role', None)

            if not request_user_id or role != 'merchant':
                return make_response(code=403, message="权限不足")

            try:
                user = User.objects.get(id=request_user_id)
                merchant_info = MerchantInfo.objects.get(merchant_id=request_user_id)
            except (User.DoesNotExist, MerchantInfo.DoesNotExist):
                return make_response(code=403, message="您不是合法的商家用户")

            data = json.loads(request.body)

            # 处理更新数据
            update_data = {}
            
            # 基本信息更新
            if 'real_name' in data:
                update_data['real_name'] = data['real_name']
            
            if 'base_daily_salary' in data:
                update_data['base_daily_salary'] = data['base_daily_salary']

            # 新增：处理员工状态更新
            if 'employment_status' in data:
                employment_status = data['employment_status']
                if employment_status in ['active', 'resigned']:
                    update_data['employment_status'] = employment_status
                else:
                    return Response({
                        "code": 400,
                        "message": "员工状态只能是 'active' 或 'resigned'"
                    }, status=400)

            # 处理时间字段
            for time_field in ['work_start_time', 'work_end_time']:
                if time_field in data and data[time_field]:
                    update_data[time_field] = datetime.strptime(data[time_field], "%H:%M:%S").time()

            # 处理工作安排
            if 'work_schedule' in data:
                schedule = data['work_schedule']
                update_data.update({
                    'monday_work': schedule.get('monday', True),
                    'tuesday_work': schedule.get('tuesday', True),
                    'wednesday_work': schedule.get('wednesday', True),
                    'thursday_work': schedule.get('thursday', True),
                    'friday_work': schedule.get('friday', True),
                    'saturday_work': schedule.get('saturday', False),
                    'sunday_work': schedule.get('sunday', False),
                })

            # 处理薪资配置
            if 'salary_config' in data:
                salary_config = data['salary_config']
                if 'late_penalty_per_minute' in salary_config:
                    update_data['late_penalty_per_minute'] = salary_config['late_penalty_per_minute']
                if 'early_leave_penalty_per_minute' in salary_config:
                    update_data['early_leave_penalty_per_minute'] = salary_config['early_leave_penalty_per_minute']
                if 'activity_bonus_per_count' in salary_config:
                    update_data['activity_bonus_per_count'] = salary_config['activity_bonus_per_count']

            # 兼容原有的单独字段格式
            for field in ['late_penalty_per_minute', 'early_leave_penalty_per_minute', 'activity_bonus_per_count']:
                if field in data:
                    update_data[field] = data[field]

            # 兼容原有的工作日字段格式
            for day in ['monday_work', 'tuesday_work', 'wednesday_work', 'thursday_work', 
                       'friday_work', 'saturday_work', 'sunday_work']:
                if day in data:
                    update_data[day] = data[day]

            return EmployeeService.update_employee_info(
                user_id=user_id,
                **update_data
            )

        except json.JSONDecodeError:
            return Response({
                "code": 400,
                "message": "请求体格式错误"
            }, status=400)
        except ValueError as e:
            return Response({
                "code": 400,
                "message": f"时间格式错误：{str(e)}"
            }, status=400)
        except Exception as e:
            return Response({
                "code": 500,
                "message": f"系统错误：{str(e)}"
            }, status=500)



@extend_schema(
    tags=["员工管理"],
    summary="获取商家员工列表（商家专用）",
    parameters=[
        AUTH_HEADER_PARAM,
        OpenApiParameter(
            name="employment_status",
            type=OpenApiTypes.STR,
            location=OpenApiParameter.QUERY,
            description="在职状态（active/resigned）",
            required=False
        )
    ]
)
class GetEmployeeListView(APIView):
    def get(self, request):
        """
        接口：获取商家员工列表
        查询参数：
        - employment_status: 在职状态（可选，默认 active）
        """
        try:
            user_id = getattr(request, 'user_id', None)
            role = getattr(request, 'role', None)

            if not user_id or role != 'merchant':
                return make_response(code=403, message="权限不足")

            try:
                user = User.objects.get(id=user_id)
                merchant_info = MerchantInfo.objects.get(merchant_id=user_id)
            except (User.DoesNotExist, MerchantInfo.DoesNotExist):
                return make_response(code=403, message="您不是合法的商家用户")

            employment_status = request.GET.get("employment_status")

            return EmployeeService.get_employee_list(
                merchant_id=merchant_info.merchant_id,
                employment_status=employment_status
            )

        except Exception as e:
            return Response({
                "code": 500,
                "message": f"系统错误：{str(e)}"
            }, status=500)


@extend_schema(
    tags=["考勤管理"],
    summary="员工打卡上班",
    parameters=[AUTH_HEADER_PARAM],
    request={
        "application/json": {
            "example": {
                "actual_time": "09:15:30"
            }
        }
    }
)
class ClockInView(APIView):
    def post(self, request):
        """
        接口：员工打卡上班
        请求体（可选）：
        {
          "actual_time": "09:15:30"  // 可选，默认当前时间
        }
        """
        try:
            user_id = getattr(request, 'user_id', None)

            if not user_id:
                return make_response(code=403, message="权限不足，需要登录")

            actual_time = None
            if request.body:
                try:
                    data = json.loads(request.body)
                    if data.get("actual_time"):
                        actual_time = datetime.strptime(data.get("actual_time"), "%H:%M:%S").time()
                except json.JSONDecodeError:
                    pass

            return AttendanceService.clock_in(
                user_id=user_id,
                actual_time=actual_time
            )

        except ValueError as e:
            return Response({
                "code": 400,
                "message": f"时间格式错误：{str(e)}"
            }, status=400)
        except Exception as e:
            return Response({
                "code": 500,
                "message": f"系统错误：{str(e)}"
            }, status=500)


@extend_schema(
    tags=["考勤管理"],
    summary="员工打卡下班",
    parameters=[AUTH_HEADER_PARAM],
    request={
        "application/json": {
            "example": {
                "actual_time": "18:30:00"
            }
        }
    }
)
class ClockOutView(APIView):
    def post(self, request):
        """
        接口：员工打卡下班
        请求体（可选）：
        {
          "actual_time": "18:30:00"  // 可选，默认当前时间
        }
        """
        try:
            user_id = getattr(request, 'user_id', None)

            if not user_id:
                return make_response(code=403, message="权限不足，需要登录")

            actual_time = None
            if request.body:
                try:
                    data = json.loads(request.body)
                    if data.get("actual_time"):
                        actual_time = datetime.strptime(data.get("actual_time"), "%H:%M:%S").time()
                except json.JSONDecodeError:
                    pass

            return AttendanceService.clock_out(
                user_id=user_id,
                actual_time=actual_time
            )

        except ValueError as e:
            return Response({
                "code": 400,
                "message": f"时间格式错误：{str(e)}"
            }, status=400)
        except Exception as e:
            return Response({
                "code": 500,
                "message": f"系统错误：{str(e)}"
            }, status=500)


@extend_schema(
    tags=["考勤管理"],
    summary="获取考勤记录",
    parameters=[
        AUTH_HEADER_PARAM,
        OpenApiParameter(
            name="start_date",
            type=OpenApiTypes.DATE,
            location=OpenApiParameter.QUERY,
            description="开始日期（YYYY-MM-DD）",
            required=False
        ),
        OpenApiParameter(
            name="end_date",
            type=OpenApiTypes.DATE,
            location=OpenApiParameter.QUERY,
            description="结束日期（YYYY-MM-DD）",
            required=False
        )
    ]
)
class GetAttendanceRecordsView(APIView):
    def get(self, request):
        """
        接口：获取考勤记录
        查询参数：
        - start_date: 开始日期（可选）
        - end_date: 结束日期（可选）
        """
        try:
            user_id = getattr(request, 'user_id', None)

            if not user_id:
                return make_response(code=403, message="权限不足，需要登录")

            start_date = request.GET.get("start_date")
            end_date = request.GET.get("end_date")

            if start_date:
                start_date = datetime.strptime(start_date, "%Y-%m-%d").date()
            if end_date:
                end_date = datetime.strptime(end_date, "%Y-%m-%d").date()

            return AttendanceService.get_attendance_records(
                user_id=user_id,
                start_date=start_date,
                end_date=end_date
            )

        except ValueError as e:
            return Response({
                "code": 400,
                "message": f"日期格式错误：{str(e)}"
            }, status=400)
        except Exception as e:
            return Response({
                "code": 500,
                "message": f"系统错误：{str(e)}"
            }, status=500)


@extend_schema(
    tags=["员工活动"],
    summary="记录员工活动",
    parameters=[AUTH_HEADER_PARAM],
    request={
        "application/json": {
            "example": {
                "order_id": "123e4567-e89b-12d3-a456-426614174000",
                "dish_id": "456e7890-e89b-12d3-a456-426614174000",
                "activity_type": "serve_dish"
            }
        }
    }
)
class RecordActivityView(APIView):
    def post(self, request):
        """
        接口：记录员工活动
        请求体：
        {
          "order_id": "订单ID",
          "dish_id": "菜品ID",
          "activity_type": "活动类型（serve_dish/cook_dish）"
        }
        """
        try:
            user_id = getattr(request, 'user_id', None)

            if not user_id:
                return make_response(code=403, message="权限不足，需要登录")

            data = json.loads(request.body)

            return EmployeeActivityService.record_activity(
                user_id=user_id,
                order_id=data.get("order_id"),
                dish_id=data.get("dish_id"),
                activity_type=data.get("activity_type")
            )

        except json.JSONDecodeError:
            return Response({
                "code": 400,
                "message": "请求体格式错误"
            }, status=400)
        except Exception as e:
            return Response({
                "code": 500,
                "message": f"系统错误：{str(e)}"
            }, status=500)


@extend_schema(
    tags=["员工活动"],
    summary="获取员工活动记录",
    parameters=[
        AUTH_HEADER_PARAM,
        OpenApiParameter(
            name="date",
            type=OpenApiTypes.DATE,
            location=OpenApiParameter.QUERY,
            description="指定日期（YYYY-MM-DD）",
            required=False
        ),
        OpenApiParameter(
            name="activity_type",
            type=OpenApiTypes.STR,
            location=OpenApiParameter.QUERY,
            description="活动类型（serve_dish/cook_dish）",
            required=False
        )
    ]
)
class GetEmployeeActivitiesView(APIView):
    def get(self, request):
        """
        接口：获取员工活动记录
        查询参数：
        - date: 指定日期（可选）
        - activity_type: 活动类型（可选）
        """
        try:
            user_id = getattr(request, 'user_id', None)

            if not user_id:
                return make_response(code=403, message="权限不足，需要登录")

            date_param = request.GET.get("date")
            activity_type = request.GET.get("activity_type")

            date_obj = None
            if date_param:
                date_obj = datetime.strptime(date_param, "%Y-%m-%d").date()

            return EmployeeActivityService.get_employee_activities(
                user_id=user_id,
                date=date_obj,
                activity_type=activity_type
            )

        except ValueError as e:
            return Response({
                "code": 400,
                "message": f"日期格式错误：{str(e)}"
            }, status=400)
        except Exception as e:
            return Response({
                "code": 500,
                "message": f"系统错误：{str(e)}"
            }, status=500)


@extend_schema(
    tags=["请假管理"],
    summary="提交请假申请",
    parameters=[AUTH_HEADER_PARAM],
    request={
        "application/json": {
            "example": {
                "leave_type": "sick_leave",
                "start_date": "2024-07-15",
                "end_date": "2024-07-16",
                "reason": "身体不适，需要休息"
            }
        }
    }
)
class SubmitLeaveRequestView(APIView):
    def post(self, request):
        """
        接口：提交请假申请
        请求体：
        {
          "leave_type": "请假类型",
          "start_date": "开始日期",
          "end_date": "结束日期",
          "reason": "请假原因"
        }
        """
        try:
            user_id = getattr(request, 'user_id', None)

            if not user_id:
                return make_response(code=403, message="权限不足，需要登录")

            data = json.loads(request.body)

            return LeaveRequestService.submit_leave_request(
                user_id=user_id,
                leave_type=data.get("leave_type"),
                start_date=datetime.strptime(data.get("start_date"), "%Y-%m-%d").date(),
                end_date=datetime.strptime(data.get("end_date"), "%Y-%m-%d").date(),
                reason=data.get("reason")
            )

        except json.JSONDecodeError:
            return Response({
                "code": 400,
                "message": "请求体格式错误"
            }, status=400)
        except ValueError as e:
            return Response({
                "code": 400,
                "message": f"日期格式错误：{str(e)}"
            }, status=400)
        except Exception as e:
            return Response({
                "code": 500,
                "message": f"系统错误：{str(e)}"
            }, status=500)


@extend_schema(
    tags=["请假管理"],
    summary="批准请假申请（商家专用）",
    parameters=[AUTH_HEADER_PARAM],
    request={
        "application/json": {
            "example": {
                "approval_notes": "同意请假，注意身体健康"
            }
        }
    }
)
class ApproveLeaveRequestView(APIView):
    def put(self, request, leave_id):
        """
        接口：批准请假申请（简化版本）
        URL 示例：/merchant/leave/approve/123e4567-e89b-12d3-a456-426614174000/
        
        说明：
        - 只记录审批时间和备注，不记录审批人信息
        - 商家通过身份验证即可审批其员工的请假
        """
        try:
            # 1. 验证用户身份和权限
            merchant_user_id = getattr(request, 'user_id', None)
            role = getattr(request, 'role', None)

            if not merchant_user_id:
                return make_response(code=401, message="未登录")
            
            if role != 'merchant':
                return make_response(code=403, message="权限不足，仅商家可以审批请假")

            # 2. 解析请求体
            data = json.loads(request.body) if request.body else {}
            approval_notes = data.get("approval_notes")

            # 3. 调用简化后的服务方法
            return LeaveRequestService.approve_leave_request(
                leave_id=leave_id,
                merchant_user_id=merchant_user_id,
                approval_notes=approval_notes
            )

        except json.JSONDecodeError:
            return Response({
                "code": 400,
                "message": "请求体格式错误"
            }, status=400)
        except Exception as e:
            logger.error(f"批准请假申请失败: leave_id={leave_id}, error={str(e)}")
            return Response({
                "code": 500,
                "message": f"系统错误：{str(e)}"
            }, status=500)


@extend_schema(
    tags=["请假管理"],
    summary="拒绝请假申请（商家专用）",
    parameters=[AUTH_HEADER_PARAM],
    request={
        "application/json": {
            "example": {
                "approval_notes": "当前业务繁忙，暂不能批准请假"
            }
        }
    }
)
class RejectLeaveRequestView(APIView):
    def put(self, request, leave_id):
        """
        接口：拒绝请假申请（简化版本）
        URL 示例：/merchant/leave/reject/123e4567-e89b-12d3-a456-426614174000/
        
        说明：
        - 只记录审批时间和拒绝原因，不记录审批人信息
        - 拒绝请假必须提供原因
        """
        try:
            # 1. 验证用户身份和权限
            merchant_user_id = getattr(request, 'user_id', None)
            role = getattr(request, 'role', None)

            if not merchant_user_id:
                return make_response(code=401, message="未登录")
            
            if role != 'merchant':
                return make_response(code=403, message="权限不足，仅商家可以审批请假")

            # 2. 解析请求体并验证
            try:
                data = json.loads(request.body)
                approval_notes = data.get("approval_notes")
                
                if not approval_notes or approval_notes.strip() == "":
                    return Response({
                        "code": 400,
                        "message": "拒绝请假必须提供原因"
                    }, status=400)
                    
            except json.JSONDecodeError:
                return Response({
                    "code": 400,
                    "message": "请求体格式错误，且拒绝请假必须提供原因"
                }, status=400)

            # 3. 调用简化后的服务方法
            return LeaveRequestService.reject_leave_request(
                leave_id=leave_id,
                merchant_user_id=merchant_user_id,
                approval_notes=approval_notes
            )

        except Exception as e:
            logger.error(f"拒绝请假申请失败: leave_id={leave_id}, error={str(e)}")
            return Response({
                "code": 500,
                "message": f"系统错误：{str(e)}"
            }, status=500)


@extend_schema(
    tags=["请假管理"],
    summary="获取请假申请列表",
    parameters=[
        AUTH_HEADER_PARAM,
        OpenApiParameter(
            name="status",
            type=OpenApiTypes.STR,
            location=OpenApiParameter.QUERY,
            description="申请状态（pending/approved/rejected）",
            required=False
        )
    ]
)
class GetLeaveRequestsView(APIView):
    def get(self, request):
        """
        接口：获取请假申请列表
        查询参数：
        - status: 申请状态（可选）

        根据用户角色返回不同数据：
        - 员工：返回自己的请假申请
        - 商家：返回所有员工的请假申请
        """
        try:
            user_id = getattr(request, 'user_id', None)
            role = getattr(request, 'role', None)

            if not user_id:
                return make_response(code=403, message="权限不足，需要登录")

            status = request.GET.get("status")

            if role == 'merchant':
                # 商家查看所有员工的请假申请
                try:
                    merchant_info = MerchantInfo.objects.get(merchant_id=user_id)
                    return LeaveRequestService.get_leave_requests(
                        merchant_id=merchant_info.merchant_id,
                        status=status
                    )
                except MerchantInfo.DoesNotExist:
                    return make_response(code=403, message="您不是合法的商家用户")
            else:
                # 员工查看自己的请假申请
                return LeaveRequestService.get_leave_requests(
                    user_id=user_id,
                    status=status
                )

        except Exception as e:
            logger.error(f"获取请假申请失败: error={str(e)}")
            return Response({
                "code": 500,
                "message": f"系统错误：{str(e)}"
            }, status=500)


@extend_schema(
    tags=["绩效管理"],
    summary="计算员工每日绩效",
    parameters=[AUTH_HEADER_PARAM],
    request={
        "application/json": {
            "example": {
                "user_id": "123e4567-e89b-12d3-a456-426614174000",
                "record_date": "2024-07-01"
            }
        }
    }
)
class CalculateDailyPerformanceView(APIView):
    def post(self, request):
        """
        接口：计算员工每日绩效（商家专用）
        请求体：
        {
          "user_id": "用户ID",  // 修改：原来是employee_id
          "record_date": "记录日期"
        }
        """
        try:
            request_user_id = getattr(request, 'user_id', None)
            role = getattr(request, 'role', None)

            if not request_user_id or role != 'merchant':
                return make_response(code=403, message="权限不足")

            data = json.loads(request.body)

            return PerformanceService.calculate_daily_performance(
                user_id=data.get("user_id"),  # 修改：原来是employee_id
                record_date=datetime.strptime(data.get("record_date"), "%Y-%m-%d").date()
            )

        except json.JSONDecodeError:
            return Response({
                "code": 400,
                "message": "请求体格式错误"
            }, status=400)
        except ValueError as e:
            return Response({
                "code": 400,
                "message": f"日期格式错误：{str(e)}"
            }, status=400)
        except Exception as e:
            logger.error(f"失败: error={str(e)}")
            return Response({
                "code": 500,
                "message": f"系统错误：{str(e)}"
            }, status=500)


@extend_schema(
    tags=["绩效管理"],
    summary="获取员工绩效记录",
    parameters=[
        AUTH_HEADER_PARAM,
        OpenApiParameter(
            name="start_date",
            type=OpenApiTypes.DATE,
            location=OpenApiParameter.QUERY,
            description="开始日期（YYYY-MM-DD）",
            required=False
        ),
        OpenApiParameter(
            name="end_date",
            type=OpenApiTypes.DATE,
            location=OpenApiParameter.QUERY,
            description="结束日期（YYYY-MM-DD）",
            required=False
        )
    ]
)
class GetPerformanceRecordsView(APIView):
    def get(self, request, user_id):
        """
        接口：获取员工绩效记录（商家专用）
        URL 示例：/merchant/performance/123e4567-e89b-12d3-a456-426614174000/
        :param user_id: 员工的用户ID (修改：原来是employee_id)
        查询参数：
        - start_date: 开始日期（可选）
        - end_date: 结束日期（可选）
        """
        try:
            request_user_id = getattr(request, 'user_id', None)
            role = getattr(request, 'role', None)

            if not request_user_id or role != 'merchant':
                return make_response(code=403, message="权限不足")

            start_date = request.GET.get("start_date")
            end_date = request.GET.get("end_date")

            if start_date:
                start_date = datetime.strptime(start_date, "%Y-%m-%d").date()
            if end_date:
                end_date = datetime.strptime(end_date, "%Y-%m-%d").date()

            return PerformanceService.get_performance_records(
                user_id=user_id,  # 修改：原来是employee_id
                start_date=start_date,
                end_date=end_date
            )

        except ValueError as e:
            return Response({
                "code": 400,
                "message": f"日期格式错误：{str(e)}"
            }, status=400)
        except Exception as e:
            return Response({
                "code": 500,
                "message": f"系统错误：{str(e)}"
            }, status=500)


@extend_schema(
    tags=["薪资管理"],
    summary="计算员工工资",
    parameters=[AUTH_HEADER_PARAM],
    request={
        "application/json": {
            "example": {
                "user_id": "123e4567-e89b-12d3-a456-426614174000",
                "start_date": "2024-07-01",
                "end_date": "2024-07-31"
            }
        }
    }
)
class CalculateSalaryView(APIView):
    def post(self, request):
        """
        接口：计算员工工资（商家专用）
        请求体：
        {
          "user_id": "员工用户ID",  // 修改：原来是employee_user_id
          "start_date": "开始日期",
          "end_date": "结束日期"
        }
        """
        try:
            request_user_id = getattr(request, 'user_id', None)
            role = getattr(request, 'role', None)

            if not request_user_id or role != 'merchant':
                return make_response(code=403, message="权限不足")

            data = json.loads(request.body)

            return SalaryService.calculate_salary(
                user_id=data.get("user_id"),  # 修改：原来是employee_user_id
                start_date=datetime.strptime(data.get("start_date"), "%Y-%m-%d").date(),
                end_date=datetime.strptime(data.get("end_date"), "%Y-%m-%d").date()
            )

        except json.JSONDecodeError:
            return Response({
                "code": 400,
                "message": "请求体格式错误"
            }, status=400)
        except ValueError as e:
            return Response({
                "code": 400,
                "message": f"日期格式错误：{str(e)}"
            }, status=400)
        except Exception as e:
            return Response({
                "code": 500,
                "message": f"系统错误：{str(e)}"
            }, status=500)


@extend_schema(
    tags=["薪资管理"],
    summary="获取工资记录列表",
    parameters=[AUTH_HEADER_PARAM]
)
class GetSalaryRecordsView(APIView):
    def get(self, request):
        """
        接口：获取工资记录列表

        根据用户角色返回不同数据：
        - 员工：返回自己的工资记录
        - 商家：返回所有员工的工资记录
        """
        try:
            user_id = getattr(request, 'user_id', None)
            role = getattr(request, 'role', None)

            if not user_id:
                return make_response(code=403, message="权限不足，需要登录")

            if role == 'merchant':
                # 商家查看所有员工的工资记录
                try:
                    merchant_info = MerchantInfo.objects.get(merchant_id=user_id)
                    return SalaryService.get_salary_records(
                        merchant_id=merchant_info.merchant_id
                    )
                except MerchantInfo.DoesNotExist:
                    return make_response(code=403, message="您不是合法的商家用户")
            else:
                # 员工查看自己的工资记录
                return SalaryService.get_salary_records(
                    user_id=user_id
                )

        except Exception as e:
            return Response({
                "code": 500,
                "message": f"系统错误：{str(e)}"
            }, status=500)


@extend_schema(
    tags=["员工活动"],
    summary="记录制作菜品活动",
    parameters=[AUTH_HEADER_PARAM],
    request={
        "application/json": {
            "example": {
                "order_id": "123e4567-e89b-12d3-a456-426614174000",
                "dish_id": "456e7890-e89b-12d3-a456-426614174000"
            }
        }
    },
    responses={
        201: {
            "description": "记录成功",
            "example": {
                "code": 201,
                "message": "制作活动记录成功",
                "data": {
                    "activity_id": "789e0123-e89b-12d3-a456-426614174000",
                    "employee_name": "张三",
                    "dish_name": "宫保鸡丁",
                    "activity_time": "2024-07-04T12:45:00Z",
                    "order_id": "123e4567-e89b-12d3-a456-426614174000",
                    "table_number": "A01",
                    "status": "已完成制作，等待上菜"
                }
            }
        }
    }
)
class RecordCookActivityView(APIView):
    def post(self, request):
        """
        记录厨师制作菜品活动
        
        请求体：
        {
          "order_id": "订单ID",
          "dish_id": "菜品ID"
        }
        
        会自动更新订单项的制作状态和时间
        """
        try:
            user_id = getattr(request, 'user_id', None)

            if not user_id:
                return make_response(code=401, message="未登录")

            data = json.loads(request.body)
            
            # 验证必填字段
            order_id = data.get("order_id")
            dish_id = data.get("dish_id")
            
            if not order_id or not dish_id:
                return Response({
                    "code": 400,
                    "message": "订单ID和菜品ID不能为空"
                }, status=400)

            return EmployeeActivityService.record_cook_activity(
                user_id=user_id,
                order_id=order_id,
                dish_id=dish_id
            )

        except json.JSONDecodeError:
            return Response({
                "code": 400,
                "message": "请求体格式错误"
            }, status=400)
        except Exception as e:
            logger.error(f"记录制作活动失败: user_id={user_id}, error={str(e)}")
            return Response({
                "code": 500,
                "message": f"系统错误：{str(e)}"
            }, status=500)


@extend_schema(
    tags=["员工活动"],
    summary="记录上菜活动",
    parameters=[AUTH_HEADER_PARAM],
    request={
        "application/json": {
            "example": {
                "order_id": "123e4567-e89b-12d3-a456-426614174000",
                "dish_id": "456e7890-e89b-12d3-a456-426614174000"
            }
        }
    },
    responses={
        201: {
            "description": "记录成功",
            "example": {
                "code": 201,
                "message": "上菜活动记录成功",
                "data": {
                    "activity_id": "789e0123-e89b-12d3-a456-426614174000",
                    "employee_name": "李四",
                    "dish_name": "宫保鸡丁",
                    "activity_time": "2024-07-04T12:50:00Z",
                    "order_id": "123e4567-e89b-12d3-a456-426614174000",
                    "table_number": "A01",
                    "status": "已完成上菜",
                    "order_completed": True
                }
            }
        }
    }
)
class RecordServeActivityView(APIView):
    def post(self, request):
        """
        记录服务员上菜活动
        
        请求体：
        {
          "order_id": "订单ID",
          "dish_id": "菜品ID"
        }
        
        会自动更新订单项状态为已完成
        如果整个订单的所有菜品都已上菜，则订单状态也会更新为已完成
        """
        try:
            user_id = getattr(request, 'user_id', None)

            if not user_id:
                return make_response(code=401, message="未登录")

            data = json.loads(request.body)
            
            # 验证必填字段
            order_id = data.get("order_id")
            dish_id = data.get("dish_id")
            
            if not order_id or not dish_id:
                return Response({
                    "code": 400,
                    "message": "订单ID和菜品ID不能为空"
                }, status=400)

            return EmployeeActivityService.record_serve_activity(
                user_id=user_id,
                order_id=order_id,
                dish_id=dish_id
            )

        except json.JSONDecodeError:
            return Response({
                "code": 400,
                "message": "请求体格式错误"
            }, status=400)
        except Exception as e:
            logger.error(f"记录上菜活动失败: user_id={user_id}, error={str(e)}")
            return Response({
                "code": 500,
                "message": f"系统错误：{str(e)}"
            }, status=500)


@extend_schema(
    tags=["员工信息"],
    summary="获取当前员工信息",
    parameters=[AUTH_HEADER_PARAM],
    responses={
        200: {
            "description": "获取成功",
            "example": {
                "code": 200,
                "message": "获取成功",
                "data": {
                    "user_id": "123e4567-e89b-12d3-a456-426614174000",
                    "username": "zhangsan",
                    "real_name": "张三",
                    "merchant_name": "美味餐厅",
                    "hire_date": "2024-01-15",
                    "work_schedule": {
                        "work_start_time": "09:00:00",
                        "work_end_time": "18:00:00"
                    },
                    "today_activities": {
                        "cook_count": 5,
                        "serve_count": 3,
                        "total_bonus": 40.0
                    }
                }
            }
        }
    }
)
class GetCurrentEmployeeInfoView(APIView):
    def get(self, request):
        """
        获取当前登录员工的详细信息
        
        包含今日活动统计和奖金信息
        """
        try:
            user_id = getattr(request, 'user_id', None)
            
            if not user_id:
                return make_response(code=401, message="未登录")

            try:
                employee = Employee.objects.get(user_id=user_id, employment_status='active')
            except Employee.DoesNotExist:
                return make_response(code=403, message="您不是在职员工")

            # 获取今日活动统计
            from django.utils import timezone
            today = timezone.now().date()
            
            from app.models import EmployeeActivity
            today_activities = EmployeeActivity.objects.filter(
                employee=employee,
                activity_time__date=today
            )
            
            cook_count = today_activities.filter(activity_type='cook_dish').count()
            serve_count = today_activities.filter(activity_type='serve_dish').count()
            total_activities = cook_count + serve_count
            total_bonus = float(total_activities * employee.activity_bonus_per_count)

            return make_response(
                code=200,
                message="获取成功",
                data={
                    "user_id": str(employee.user.id),
                    "username": employee.user.username,
                    "real_name": employee.real_name,
                    "merchant_name": employee.merchant.shop_name,
                    "hire_date": employee.hire_date.isoformat(),
                    "work_schedule": {
                        "work_start_time": employee.work_start_time.strftime("%H:%M:%S"),
                        "work_end_time": employee.work_end_time.strftime("%H:%M:%S"),
                        "monday": employee.monday_work,
                        "tuesday": employee.tuesday_work,
                        "wednesday": employee.wednesday_work,
                        "thursday": employee.thursday_work,
                        "friday": employee.friday_work,
                        "saturday": employee.saturday_work,
                        "sunday": employee.sunday_work,
                    },
                    "salary_info": {
                        "base_daily_salary": float(employee.base_daily_salary),
                        "activity_bonus_per_count": float(employee.activity_bonus_per_count),
                        "late_penalty_per_minute": float(employee.late_penalty_per_minute),
                        "early_leave_penalty_per_minute": float(employee.early_leave_penalty_per_minute)
                    },
                    "today_activities": {
                        "cook_count": cook_count,
                        "serve_count": serve_count,
                        "total_activities": total_activities,
                        "total_bonus": total_bonus
                    }
                }
            )

        except Exception as e:
            logger.error(f"获取员工信息失败: user_id={user_id}, error={str(e)}")
            return Response({
                "code": 500,
                "message": f"系统错误：{str(e)}"
            }, status=500)